require 'open-uri'
require 'nokogiri'

require File.dirname(__FILE__) + "/../config/environment"

def get_stats_by_url url
  stats = {}
  this_result = Nokogiri::HTML(open(url))
    
  this_result.css("span").each { |s| stats["description"] = s.text if s["id"].gsub(/\s+/,'') == "preview-local-desc" rescue nil }
  
  this_result.css("table").each do |table|
    next if table["id"].nil?
    next if table["id"].gsub(/\s+/, "") != "attributeTable"
    
    table_cell_text = table.css("td").map { |td| td.text } 
    table_cell_text.each_index do |index|
      case table_cell_text[index].gsub(/\s+/, "")
      when "Price"
        stats["price"] = table_cell_text[index + 1].scan(/(\d+),(\d+)/)[0].join.to_i rescue 0
      when "Model"
        stats["name"] = table_cell_text[index + 1]
      when "Kilometers"
        stats["km"] = table_cell_text[index + 1].to_i
        stats["km"] *= 1000 if stats["km"] < 1000
      when "Transmission"
        stats["transmission"] = table_cell_text[index + 1]
      when "Year"
        stats["year"] = table_cell_text[index + 1]
      when "DateListed"
        puts stats["date_listed"]
        stats["date_listed"] = table_cell_text[index + 1]
      when "LastEdited"
        stats["date_updated"] = table_cell_text[index + 1]
      else
      end 
    end
  end
  
  stats
end

def create_vehicle_from_url url
  new_vehicle = VehicleResult.find_or_create_by_url url
  
  stats = get_stats_by_url url
  
  stats.each do |stat,value|
    new_vehicle[stat] = value
  end
  
  new_vehicle.save
  
  puts "Created vehicle \"#{new_vehicle.name}\""
  
  new_vehicle
end

def update_vehicle_by_url url
  # Only checking Price at this point!
  vehicle = VehicleResult.find_by_url url
  stats = get_stats_by_url url
  updated = false
  
  if stats["price"] != vehicle.price
    old_price = vehicle.price
    vehicle.price = stats["price"]
    vehicle.save
    updated = true
    puts "Updated vehicle \"#{vehicle.name}\".  Old Price=#{old_price} New Price=#{vehicle.price}"
  else
    puts "No changes for vehicle \"#{vehicle.name}\""
  end
  
  {:vehicle => vehicle, :updated? => updated, :old_price => old_price}
end

def execute_search(search_url)
  results_to_send = []
  doc = Nokogiri::HTML(open(search_url))
  
  doc.css("tr").each do |row|
    next if row["class"].gsub(/\s+/, "") != "resultsTableSB rrow".gsub(/\s+/, "") rescue next
   
    url = ""
    price = 0
   
    row.css("a").each { |a| url = a["href"] if a["class"].gsub(/\s+/, "") == "adLinkSB" rescue next }
    row.css("td").each { |td| price = td.text if td["class"].gsub(/\s+/, "") == "prc" rescue next }
    price = price.scan(/(\d+),(\d+)/)[0].join.to_i rescue 0
   
    next if url.empty?
    
    existing_vehicle_check = VehicleResult.find_by_url(url)
    
    if existing_vehicle_check.nil?
      vehicle = create_vehicle_from_url url
      results_to_send << {:vehicle => vehicle}
    elsif existing_vehicle_check.price != price
      old_price = existing_vehicle_check.price
      existing_vehicle_check.price = price
      existing_vehicle_check.save
      results_to_send << {:vehicle => existing_vehicle_check, :changes => {:old_price => old_price}}
      puts "Updated #{existing_vehicle_check.name}!  Old price=#{old_price}, new price=#{price}"
      # changes = update_vehicle_by_url url
      # if (changes[:updated?] == true)
        # results_to_send << {:vehicle => changes[:vehicle], :changes => changes}
      # end
    end
   
  end
  
  results_to_send
end

while 1
  config = Nokogiri.Slop(File.read("config.xml"))
  
  search_links = []
  config.options.searches.url.each { |url| search_links << url.text unless url.text.empty? }
  
  search_delay_minutes = config.options.search_delay_minutes.text.to_i
  search_delay_minutes = 10 if search_delay_minutes == 0
  
  destination_emails = []
  config.options.send_to.email.each { |address| destination_emails << address.text unless address.text.empty? }
  
  results_to_send = []
  search_links.each { |search| results_to_send << execute_search(search) } rescue nil
  
  results_to_send.flatten! 

  if results_to_send.empty?
    puts "#{Time.now} - No new results.  Will search again in #{search_delay_minutes}"
  else
    VehicleMailer.send_vehicle_info(destination_emails, results_to_send).deliver rescue nil
  end

  sleep search_delay_minutes*60
end
 


